package cn.codenest.sagaservice1.service.impl;

import cn.codenest.sagaservice1.service.OrderService;
import com.rabbitmq.client.ReturnCallback;
import com.rabbitmq.client.ShutdownSignalException;
import org.springframework.amqp.AmqpConnectException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author ：Hyman
 * @date ：Created in 2021/8/5 17:16
 * @description：
 * @modified By：
 * @version: $
 */
public class OrderServiceImpl implements OrderService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void createOrder(String order) {
        String orderEvent = saveOrderToDb(order);
        try {
            Message message = new Message(orderEvent.getBytes());
            rabbitTemplate.setMandatory(true);
            rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
                @Override
                public void returnedMessage(ReturnedMessage returnedMessage) {
                    saveOrderEventToDb(orderEvent);
                }
            });
            rabbitTemplate.send("TestDirectExchange", "TestDirectQueue", message);
        } catch (ShutdownSignalException e) {
            System.out.println("交换机故障或者不存在。");
            saveOrderEventToDb(orderEvent);
        } catch (AmqpConnectException e) {
            System.out.println("服务器连接失败。");
            saveOrderEventToDb(orderEvent);
        }
    }

    private String saveOrderToDb(String order) {
        return order;
    }

    private void saveOrderEventToDb(String order) {
    }

}
